<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/10/9 0009
 * Time: 11:57
 */

namespace App\Http\Controllers\Admin;

use App\Models\Admin\DepositIn;
use App\Models\Admin\DepositOut;
use App\Models\Admin\Order;
use App\Models\Admin\PosOrder;
use App\Models\Admin\RuzhuMerchantBasic;
use App\Models\Admin\Sms;
use App\Models\Admin\Tools;
use App\Models\Admin\Withdraw;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;

class SettleController extends CommonController
{
    //视图前缀
    const VIEW_PREFIX = 'admin.settle.';
    //每日最高可提现金额
    const MAX_DAY = 2000000;
    //费率
    const RATE = 0.005;
    //关联用户ID
    private $sid;
    //入驻商户ID
    private $uid;

    /**
     * SettleController constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->checkLogin();
        $this->sid = $_SESSION['node_id'];
        $this->uid = $_SESSION['admin_uid'];
    }

    /**
     * 手机支付款或POS机支付款提现列表
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function withdrawList(Request $request)
    {
        $data = [];
        $withDraw = new Withdraw();
        switch ($request->get('source_type')) {
            case '1'://手机支付款
                $orderModel = new Order();
                $data['income'] = $orderModel->getIncome($this->uid);
                $data['realIncome'] = $orderModel->getRealIncome($this->uid);
                $data['cashed'] = $withDraw->getCashed($this->sid, 1);
                $data['lists'] = $withDraw->getLists($this->sid, 1, $request->input());
                break;
            case '2'://POS机支付款
                $posOrder = new PosOrder();
                $data['income'] = $posOrder->getIncome($this->sid);
                $data['realIncome'] = $posOrder->getRealIncome($this->sid);
                $data['cashed'] = $withDraw->getCashed($this->sid, 2);
                $data['lists'] = $withDraw->getLists($this->sid, 2, $request->input());
                break;
            case '3'://让利存款
                $data['income'] = with(new DepositIn())->getTotal($this->sid,$this->uid);
                $data['cashed'] = $withDraw->getCashed($this->sid, 3);
                $data['realIncome'] = with(new DepositOut())->getUnfreeze($this->sid);
                $data['lists'] = $withDraw->getLists($this->sid, 3, $request->input());
                break;
            default:
                return abort('403', '参数错误');
        }
        if ($request->has('export') and $request->get('export') == 'true') {
            //开始导出
            Tools::exportFileNormal('提现导出表', ['序号', '提现状态', '提现金额', '手续费', '申请时间'], Withdraw::parseForExcel($data['lists']->items()));
        }
        return view(self::VIEW_PREFIX . 'withdraw_list', ['data' => $data]);
    }


    /**
     * 完善商户卡信息
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function editBankInfo(Request $request){
        if($request->isMethod('post')){

        }else{
            return view(self::VIEW_PREFIX.'edit_bank_info');
        }
    }


    /**
     * 申请提现
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function applyWithdraw(Request $request)
    {
        $data = [];
        //获取到账银行信息
        $data['bankInfo'] =(new RuzhuMerchantBasic())->getInfo($this->sid);
        $data['rate'] = self::RATE;//费率 TODO
        if (empty($data['bankInfo'])) {
//           return redirect('settle/edit_bank_info');
            return '<h4>请补全您的银行卡信息</h4>';
        }
        $data['bankInfo']->bankName = Tools::getBankName($data['bankInfo']->bank_code);
        //获取可提现最大金额
        $withDraw = new Withdraw();
        $data['extraCash'] = self::MAX_DAY - $withDraw->getCashDay($this->sid);//今日剩余可提现金额
        switch ($request->get('source_type')) {
            case '1':
                $order = new Order();
                $data['enableCash'] = $order->getRealIncome($this->uid) - $withDraw->getCashed($this->sid, 1);
                break;
            case '2':
                $posOrder = new PosOrder();
                $data['enableCash'] = $posOrder->getRealIncome($this->sid) - $withDraw->getCashed($this->sid, 2);
                break;
            case '3':
                $data['enableCash'] = with(new DepositOut())->getUnfreeze($this->sid) - $withDraw->getCashed($this->sid, 3);
                break;
            default:
                return abort(403, '参数错误');
        }

        if ($request->isXmlHttpRequest()) {
            //验证验证码
            $phone_verify_code = Session::get('phone_verify_code');
//            $phone_verify_code = 1234;
            if ($request->phone_verify_code != $phone_verify_code) {
                return response()->json([
                    'status' => 0,
                    'msg' => '短信验证码错误',
                    'data' => ''
                ]);
            }
            //验证金额
            if ($request->input('apply_amount') > $data['enableCash']) {
                return response()->json([
                    'status' => 0,
                    'msg' => '您提取的金额超过可提现最大金额',
                    'data' => ''
                ]);
            }
            //todo 0改为100
            if ($request->input('apply_amount') < 0) {
                return response()->json([
                    'status' => 0,
                    'msg' => '最低提取金额为100元',
                    'data' => ''
                ]);
            }
            if ($request->input('apply_amount') > $data['extraCash']) {
                return response()->json([
                    'status' => 0,
                    'msg' => '您提取的金额超过每日限额',
                    'data' => ''
                ]);
            }
            DB::beginTransaction();
            $res = DB::table('o2oadmin_withdraw')->insert([
                'id' => Withdraw::getNextSeq(),
                'nodeid' => $this->sid,//关联用户表ID
                'apply_status' => 1,
                'apply_time' => date('Y-m-d H:i:s'),
                'transfer_amount' => $request->input('apply_amount') - $request->input('apply_amount') * $data['rate'],
                'poundage' => $request->input('apply_amount') * $data['rate'],//TODO 最低1元? 向上取整
                'cardholder' => $data['bankInfo']->bank_account_name,//持卡人姓名
                'bank_card' => $data['bankInfo']->bank_account_no,//银行卡号
                'bank_name' => $data['bankInfo']->bank_name,//银行卡名字
                'apply_amount' => $request->input('apply_amount'),
                'source_type' => $request->input('source_type'),
                'snumber'=> date('YmdHis').rand(10000,99999)
            ]);
            if ($res) {
                DB::commit();
                return response()->json([
                    'status' => 1,
                    'msg' => '申请成功',
                    'data' => ''
                ]);
            } else {
                DB::rollBack();
                return response()->json([
                    'status' => 0,
                    'msg' => '请求失败,请联系客服',
                    'data' => ''
                ]);
            }
        } else {
            return view(self::VIEW_PREFIX . 'apply_withdraw', ['data' => $data]);
        }
    }


    /**
     * 发送短信验证码
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function send_sms(Request $request)
    {
        if (!$request->isXmlHttpRequest()) {
            return response()->json([
                'status' => 0,
                'msg' => '请求方式错误',
                'data' => ''
            ]);
        }
        //实例化模型
        $sms = new Sms();
        //生成随机6为验证码
        $str = '1234567890';
        $rand_verify_code = '';
        for ($i = 0; $i < 6; $i++) {
            $rand_verify_code .= $str{mt_rand(0, 9)};
            $request->session()->put('phone_verify_code', $rand_verify_code);
        }
        //短信模板参数
        $parameter = array(
            "DateTime" => date('Y年m月d日 H:i:s'),
            "VerifiCode" => $rand_verify_code,
            "TemplateNo" => 'c015d86f245c841fc447d21d6f2c42d0',
        );
        //获取需要接收验证码的手机号码    MERCHANT_ID
        $bankInfo = with(new RuzhuMerchantBasic())->getInfo($this->sid);
        $phone_number = $bankInfo->nodecode;
        if (\Cache::has('sms_' . $phone_number)) {
            return response()->json([
                'status' => 0,
                'msg' => '短信发送过快',
                'data' => ''
            ]);
        }
        if (!Tools::checkMobileValidity($phone_number)) {
            return response()->json([
                'status' => 0,
                'msg' => '手机号格式有误',
                'data' => ''
            ]);
        }
        //发送短信验证码
        $res = $sms->msg($phone_number, '操作验证', $parameter);
        $res = json_decode($res);
//        \Log::error(serialize($res));//s:61:"{"Content":null,"Success":true,"StatusCode":0,"Message":null}"//短信发送成功后的JSON
        if ($res->Success == true) {
            \Cache::put('sms_' . $phone_number, '1', 1);//1分钟缓存
            return response()->json([
                'status' => 1,
                'msg' => '发送成功',
                'data' => ''
            ]);
        } else {
            return response()->json([
                'status' => 0,
                'msg' => '短信发送失败',
                'data' => ''
            ]);
        }
    }

    /**
     *  存款解冻记录列表
     *
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function deposit(Request $request)
    {
        if ($request->get('unfreeze') == 'true') {
            $model = new DepositOut();
            return view(self::VIEW_PREFIX . 'deposit_unfreeze', ['data' => $model->getLists($this->sid)]);//解冻记录
        } else {
            $model = new DepositIn();
            return view(self::VIEW_PREFIX . 'deposit', ['data' => $model->getLists($this->sid,$this->uid)]);//存款记录
        }
    }

}